package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.itheima.dao.UserDao;
import com.itheima.pojo.Menu;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户服务接口实现类
 */
@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private JedisPool jedisPool;

    /**
     * 根据用户查询用户对象
     *
     * @param username
     * @return
     */
    @Override
    public User findUserByUsername(String username) {
        return userDao.findUserByUsername(username);
    }

    /**
     * 获取当前登录用户菜单
     */
    @Override
    public List<Menu> getMenuListByUserName(String username) {

        Jedis jedis = jedisPool.getResource();
        List<Menu> menuList = JSON.parseObject(jedis.get(username), List.class);
        if (menuList == null) {
            //根据当前登录用户获取一级菜单
            menuList = userDao.getMenuListByUserName(username);
            //遍历获取二级菜单
            if (menuList != null && menuList.size() > 0) {
                for (Menu mn : menuList) {
                    //设置二级菜单查询条件
                    Map paramsMap = new HashMap();
                    paramsMap.put("username", username);
                    paramsMap.put("parentMenuId", mn.getId());
                    //获取二级菜单
                    List<Menu> childrenMenu = userDao.findMenuByParentMenuId(paramsMap);
                    //补全二级菜单
                    mn.setChildren(childrenMenu);
                }
            }
            jedis.set(username, JSON.toJSONString(menuList));
        }

        //返回完整菜单
        return menuList;
    }

    /**
     * 修改密码
     * @param map
     */
    @Override
    public void updatePassword(Map map) {
        //根据用户名获取用户
        User user = findUserByUsername(map.get("username").toString());

        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        //校验密码
        boolean flag = encoder.matches(map.get("password").toString(), user.getPassword());
        if (flag){
            //
            String newPassword = encoder.encode(map.get("newPassword").toString());
            user.setPassword(newPassword);
            userDao.updatePassword(user);
        }else {
            throw new RuntimeException("密码错误,请重新输入");
        }
    }
}
